<?php

namespace App\Supports\Payment\Methods\Alipay;

use Exception;
use App\Supports\Payment\Methods\Method;
use Illuminate\Validation\ValidationException;
use App\Supports\Payment\Contracts\MethodRefund;

class RefundOrder extends Method implements MethodRefund
{
	public function validate($order = null)
	{
		if (! $order->isPaid()) {
			abort(403, '目标订单未支付');
		}
		// if ($refund->order->isClosed()) {
		// 	abort(403, '目标订单已关闭');
		// }
		// if ($refund->order->isCancelled()) {
		// 	abort(403, '目标订单已取消');
		// }
		// if ($refund->order->has_refund) {
		// 	abort(403, '目标商品已退款');
		// }
		if ($order->paid_method !== 'alipay') {
			abort(403, '目标订单不能通过支付宝退款');
		}
	}
	
	public function info($order = null)
	{
		$outTradeNo = 'order_'.$order->number;
		
		
		return [
			'out_trade_no' => $outTradeNo,
			'refund_amount' => $order->total_amount,
			'out_request_no' => $order->number,
			'notify_url' => route('web.payments.wxpay.notify')
		];
	}
	
	public function refund($order = null)
	{
		$this->validate($order);
		
		try {
			$info = $this->info($order);
			return $this->channel->refund($info);
		} catch (Exception $exception) {
			throw ValidationException::withMessages(['err' => '支付暂不可用!']);
		}
	}
}
